import numpy as np
import matplotlib.pyplot as mp
import math
from numpy.polynomial import Polynomial


# f(x) = x**4 - 4 * x**3 - 6 * x**2 - 16 * x + 4
# 使用牛顿法求f(x)的极小点
def objFun1(x):
    y = 3 * math.pow(x, 3.0) - 4.0 * x + 2.0
    return y


def objFun2(P, x):
    ret = 0
    size = len(P) - 1
    for coef in P:
        ret += coef * math.pow(x, size)
        size -= 1
    return ret


P = [1, -4, -6, -16, 4]
Q = np.polyder(P)
R = np.polyder(Q)
a = 3
e = 0.001
b = a - (objFun2(Q, a) / objFun2(R, a))
# p1 = poly.Polynomial(coef=Q)
# ret = objFun2([2, 1, 1], 1)
while abs(b - a) >= e:
    a = b
    b = a - (objFun2(Q, a) / objFun2(R, a))

ret = objFun2(P, b)

print(f"这个函数的极小点是{b}, 函数的极值是{ret}")

